<template>
  <!--  -->
  <!-- 文件预览：txt文本预览） -->
  <!--  -->
  <div class="code">
    <div class="top-op">
        <div class="encode-select">
            <!-- 下拉框    @change：选择时触发-->
            <el-select clearable placeholder="选择编码" v-model="encode" @change="changeEncode">
                <el-option value="utf8" label="utf8编码"></el-option>
                <el-option value="gbk" label="gbk编码"></el-option>
            </el-select>
            <div class="tips">乱码了？切换编码</div>
        </div>
        <div class="copy-btn">
            <el-button type="primary" @click="copy">复制</el-button>
        </div>
    </div>
    <!-- 代码高亮组件 main.js第12行引入 -->
    <highlightjs autodetect :code="txtContent"></highlightjs>
  </div>
</template>

<script setup>
import useClipboard from "vue-clipboard3";     //读取剪切板内容，依赖下载在package.json第27行
const { toClipboard } = useClipboard();        //往剪切板写入
import { ref, reactive, getCurrentInstance, onMounted, computed, onUnmounted } from "vue";
const { proxy } = getCurrentInstance();

const props = defineProps({
    url: {
        type: String,
    },
});

const codeRef = ref();
const txtContent = ref(""); //容器
const blobResult = ref();   //后端返回的流
const encode = ref("utf8"); //多选选择所绑定的编码

//获取预览文件的流
const readTxt = async () => {
    let result = await proxy.Request({
        url: props.url,
        responseType: "blob",  //响应数据以流的形式返回，不是json
    });
    if (!result) {
        return;
    }
    blobResult.value = result;
    showTxt();
};


//改变编码
const changeEncode = (e) => {
    encode.value = e;
    showTxt();
};


//读取文件
const showTxt = () => {
    const reader = new FileReader();  //创建文件读取流
    reader.onload = () => {           //一个方法，将读取到的流赋值给txtContent
        let txt = reader.result;
        txtContent.value = txt;
    };
    reader.readAsText(blobResult.value, encode.value);     //读取流
};


//在Vue3 中,onMounted 是一个生命周期钩子函数,用于在组件渲染后执行（在<script>标签头部引入）
onMounted(() => {
    readTxt();
});


//复制按钮
const copy = async () => {
    await toClipboard(txtContent.value);   //将txtContent往剪切板中写入
    proxy.Message.success("复制成功");
};

</script>

<style lang="scss" scoped>
.code {
    width: 100%;
    .top-op {
        display: flex;
        align-items: center;
        justify-content: space-around;
    }
    .encode-select {
        flex: 1;
        display: flex;
        align-items: center;
        margin: 5px 10px;
        .tips {
            margin-left: 10px;
            color: #828282;
        }
    }
    .copy-btn {
        margin-right: 10px;
    }
    pre {
        margin: 0px;
    }
}
</style>